// $Id$
//////////////////////////////////////////////////////////////////////////
// Purpose : make a hole file
//////////////////////////////////////////////////////////////////////////

#include <errno.h>
#include <stdio.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>

int WriteFileUseFd(int fd, const char *msg)
{
	size_t msg_len;
	size_t n;

	msg_len = strlen(msg);
	if (msg_len <= 0)
	{
		return -1;
	}
	
	n = write(fd, msg, msg_len);
	if (n < msg_len)
	{
		return -1;
	}

	return 0;
}

void CreateAHoleFile()
{
	int hole_file_fd;
	const char push_msg[] = "abcdefghij";

	// Create a hole file and check exists
	hole_file_fd = open("hole", O_CREAT | O_TRUNC | O_RDWR, S_IRUSR | S_IWUSR);

	if (hole_file_fd == -1)
	{
		return;
	}

	// Write 10B data in the head of the file
	WriteFileUseFd(hole_file_fd, push_msg);
	// Write 4096B hole data
	lseek(hole_file_fd, 16384, SEEK_CUR);
	// Write 10B data in the end of the file
	WriteFileUseFd(hole_file_fd, push_msg);
	close(hole_file_fd);
}

void CreateANoHoleFile()
{
	int no_hole_fd;
	const char msg[] = "b";

	no_hole_fd = open("no_hole", O_CREAT | O_TRUNC | O_RDWR, S_IRUSR | S_IWUSR);

	if (no_hole_fd == -1)
	{
		return;
	}

	for(int i = 0; i <= 16384 + 20; i ++)
	{
		WriteFileUseFd(no_hole_fd, msg);
	}
	close(no_hole_fd);
}

int main(int argc, char **argv)
{
	if (errno != 0)
	{
		errno = 0;
	}

	CreateAHoleFile();

	if (errno)
	{
		perror(argv[0]);
		return -1;
	}

	CreateANoHoleFile();

	if (errno)
	{
		perror(argv[0]);
		return -1;
	}

	return 1;
}
